Java Variable Types
In Java, variables are used to store data that can be manipulated or accessed during program execution. Java supports various types of variables based on the data they hold and their scope. Let's explore the different Java variable types:
1. Local Variables
Local variables are declared within a method, constructor, or block and are accessible only within that specific scope. They must be initialized before use.
public void exampleMethod() {
int localVar = 10; // Local variable
System.out.println(localVar);
}
2. Instance Variables(Non-static Fields)
Instance variables are declared within a class but outside any method, constructor, or block. Each instance of the class (object) has its own copy of instance variables.
public class MyClass {
int instanceVar; // Instance variable
}
3. Class Variables(Static Fields)
Class variables, also known as static fields, are declared with the static keyword within a class but outside any method, constructor, or block. They are shared among all instances of the class.
public class MyClass {
static int classVar; // Class variable
}
4. Parameters (Method Arguments)
Parameters are variables declared in the method signature and are used to pass values to methods. They act as local variables within the method scope.
public void exampleMethod(int param1, String param2) {
// param1 and param2 are method parameters
}
5. Constants (Final Variables)
Constants are variables whose values cannot be changed once assigned. They are typically declared with the final keyword.
public class ConstantsExample {
final int CONSTANT_VALUE = 100; // Constant variable
}